package pa3;

import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.Properties;

import pa3.SystemManager;

/**This class is used only for providing an entry point to the system. It manages a 
 * list of the hosts which are registered in the system in order to help new hosts 
 * to connect directly to the others. It is not involved in the failure detection algorithm.
 * 
 * @author Flo
 *
 */
public class SystemManagerImpl extends UnicastRemoteObject implements SystemManager, Runnable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 7143660591281321452L;
	private HashMap<String, Host> registeredHosts;
	protected SystemManagerImpl() throws RemoteException {
		super();
		registeredHosts = new HashMap<String, Host>();
	}

	/**
	 * Gets called by a host who wants to (re)join the group of already registered hosts.
	 * @return the hosts registered in the system.
	 */
	@Override
	public synchronized HashMap<String, Host> register(Host newHost, String hostName) throws RemoteException {
		if(!registeredHosts.containsKey(hostName)){
			registeredHosts.put(hostName, newHost);
		}
		return (HashMap<String, Host>)registeredHosts.clone();
	}

	public static void main(String args[]){
		
	}

	@Override
	public void run() {
		try {
			//the commented block will be needed when testing the whole thing with mor than one computers
			/*
			Properties systemProperties = 
			      new Properties( System.getProperties() );
			systemProperties.put("java.rmi.server.hostname","10.0.0.3");
			systemProperties.put("java.security.policy", "policy");
			System.setProperties(systemProperties);
			if(System.getSecurityManager() == null){
				System.setSecurityManager(new RMISecurityManager());
			}
			*/
			Registry registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);			
			registry.rebind(SystemManager.SERVICENAME, this);
			System.out.println("Bound SystemManager in local registry.");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
